import React from 'react';
import { createHashRouter, Navigate } from 'react-router-dom';

import Layout from '@/layout';
import NotPermission from '@/views/403/index';
import NotFound from '@/views/404/index';
import Login from '@/views/login/index';
import Welcome from '@/views/welcome/index';

import AuthLoader from './AuthLoader';
import lazyLoad from './LazyLoad';

/**
 * 路由配置
 */
export const routes = [
    {
        path: '/',
        element: <Navigate to="/welcome" />
    },
    {
        path: '/login',
        element: <Login />
    },
    {
        id: 'layout',
        element: <Layout />,
        loader: AuthLoader,
        // 阻止loader重复加载，每次路由切换都重新加载
        shouldRevalidate: () => false,
        children: [
            {
                path: '/welcome',
                element: <Welcome />,
                meta: {
                    // 登录后无需路由权限即可访问
                    auth: false
                }
            },
            {
                path: '/dashboard',
                element: lazyLoad(React.lazy(() => import('@/views/dashboard')))
            },
            {
                path: '/userList',
                element: lazyLoad(React.lazy(() => import('@/views/system/user')))
            },
            {
                path: '/menuList',
                element: lazyLoad(React.lazy(() => import('@/views/system/menu')))
            },
            {
                path: '/roleList',
                element: lazyLoad(React.lazy(() => import('@/views/system/role')))
            },
            {
                path: '/deptList',
                element: lazyLoad(React.lazy(() => import('@/views/system/dept')))
            }
        ]
    },
    {
        path: '/403',
        element: <NotPermission />
    },
    {
        path: '/404',
        element: <NotFound />
    },
    {
        // 兜底路由，匹配所有未定义的路由
        path: '*',
        // 重定向到404页面，可以同步浏览器地址栏路由 /404，优化体验
        element: <Navigate to="/404" />
    }
];

/**
 * 推荐API路由: 可以使用 loader(类似拦截器) action
 * createHashRouter适合B端后台管理系统
 * createBrowserRouter适合C端应用，需后端处理资源和接口配置（如nginx）
 */
const router = createHashRouter(routes, {
    // 应用基础路径，用于部署在非根目录时使用，对应vite.base配置项
    basename: import.meta.env.BASE_URL,
    future: {
        v7_relativeSplatPath: true
    }
});

export default router;
